#!/usr/bin/env python

# Based on an example for retrieving SMS data as posted in:
#
#   http://code.google.com/p/pygooglevoice/issues/detail?id=22#c13

from googlevoice import Voice
import re
import sys
import json
import time
import os
import os.path

base = "./mirror/"

vxmFeeds = ['voicemail']
smsFeeds = ['sms']
mp3Feeds = ['recorded', 'voicemail']

def extractMessages(json):
    for message in iter(json['messages']):
        yield json['messages'][message]
    return

def stripDetails(json):
    json['relativeStartTime'] = ""
    
    return json

def getMessagesFromIDs(voice, ids):
    msgs = []
    for id in ids:
        getattr(voice,'message')(terms={ 'messageId':id })
        msgs.append( getattr(voice,'message').data['messages'] )
    return msgs

def getMessageIDs(voice, feed):
    msgs = []
    page = 0
    while True:
        page += 1
        getattr(voice,feed)(terms={ 'page':('p%d' % page) })
        
        jsonData = getattr(voice,feed).data
        
        if 'messages' not in jsonData or len(jsonData['messages']) < 1:
            break
        for message in jsonData['messages']:
            msgs.insert(0, jsonData['messages'][message]['id'])
        print 'page %d' % page
    return msgs

def burstMessage(message):
    if 'children' not in message or not message['children']:
        return [message]
    else:
        children = list(message['children'])
        message['children'] = ''
        list.sort(children, key=lambda child: child['startTime'])
        sequence = 0
        if len(children) > 1:
            sequence = 1
        for child in children:
            if sequence > 0:
                child['x-sequence'] = sequence
                sequence += 1
            for key in iter(message):
                if key not in child:
                    child[key] = message[key]
        return children

def saveMessages(feed, messages):
    for message in messages:
        for messageKey in message:
            for burst in burstMessage(message[messageKey]):
                saveMessage(burst, feed)

def saveMessage(message, feed):
    outputDir = base+feed+'/'
    message = stripDetails(message)
    
    name = time.strftime("%Y%m%d %H%M%S",time.localtime(int(message['startTime'])/1000))
    if message['phoneNumber'] != "":
        name += " "+message['phoneNumber']
    else:
        name += " Unknown"
    if feed in smsFeeds:
        name += " "+message['conversationId']
        if 'x-sequence' in message:
            name += "-"+str(message['x-sequence'])
        else:
            name += "-1"
    else:
        name += " "+message['id']
    name = name.lower()
    print name
    ensureDirectory(outputDir)
    f = open(outputDir+name+'.txt', 'w')
    f.write(json.dumps(message,sort_keys=True, indent=4))
    f.close()
    if feed in mp3Feeds:
        voice.download(message['id'], outputDir, name+".mp3")

def ensureDirectory(path):
    if not os.path.isdir(path):
        try:
            os.makedirs(path)
        except OSError, e:
            if e.errno != errno.EEXIST:
                raise

voice = Voice()
voice.login()

for feed in ['received', 'placed', 'missed', 'sms', 'recorded', 'voicemail']:
    print feed
    messages = getMessageIDs(voice, feed)
    messages = getMessagesFromIDs(voice, messages)
    saveMessages(feed, messages)
